package com.log4j.lookup

import org.apache.logging.log4j.Level
import org.apache.logging.log4j.core.LogEvent
import org.apache.logging.log4j.core.config.plugins.Plugin
import org.apache.logging.log4j.core.lookup.AbstractLookup
import org.apache.logging.log4j.core.lookup.StrLookup
import kotlin.math.max
import kotlin.math.min

/**
 * OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL
 */
@Plugin(name = "level", category = StrLookup.CATEGORY)
class LevelLookup : AbstractLookup() {

    companion object {

        val levels: Array<out Level> by lazy {
            Level.values()
        }

    }

    override fun lookup(event: LogEvent?, key: String?): String? {

        if (key.isNullOrBlank()) return null

        var operator = ""
        var chars = key.split("+")
        var key = key
        var value: Int? = null
        if (chars.size > 1) {
            key = chars[0]
            operator = "+"
            value = chars[1].toIntOrNull()
        } else {
            chars = key.split("-")
            if (chars.size > 1) {
                key = chars[0]
                operator = "-"
                value = chars[1].toIntOrNull()
            }
        }
        if (value == null) return key
        return when (operator) {
            "+" -> {
                var index = levels.indexOfFirst { it.name() == key }
                if (index > -1) {
                    index = min(index + value, levels.size - 1)
                    levels[index].name()
                } else key
            }
            "-" -> {
                var index = levels.indexOfFirst { it.name() == key }
                if (index > -1) {
                    index = max(index - value, 0)
                    levels[index].name()
                } else key
            }
            else -> key
        }
    }

}